from selenium import webdriver

from framework.basetest import BaseTest


class SeleniumBaseTest(BaseTest):

    def setUp(self, config, **kwargs):
        super().setUp(config)

    def tearDown(self):
        self.logger.info('自动化测试程序结束')
        if self.driver:
            self.driver.quit()

    def init_driver_by_browser_name(self, config, **kwargs):
        self.logger.info('在HeadSpin上运行浏览器自动化测试')
        device_name = None
        for k, v in kwargs.items():
            self.logger.debug(f'Optional arguments {k} = {v}')
            if k == 'deviceName':
                device_name = v

        if device_name is None:
            raise ValueError('自动化测试将在HeadSpin上运行，请提供浏览器名称 deviceName?')

        # 从HeadSpin API 获取基础 Desire Capabilities
        udid = self.hs_api.get_browser_udid_by_name(device_name)
        desire_cap = self.hs_api.get_device_capabilities(udid)
        selenium_url = self.hs_api.get_driver_url_for_device(udid)

        # 添加本地 Desire Capabilities 参数
        desire_cap_local = self.hs_api.get_browser_local_config_by_name(device_name)

        # 整合本地与hs desire capability
        desire_cap.update(desire_cap_local)

        self.logger.info(f'The selenium driver url: {selenium_url}')
        self.logger.info(f'The desire cap: {desire_cap}')
        self.driver = webdriver.Remote(selenium_url, desire_cap)
